package com.sgb.kjwl.utils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Environment;
import android.view.Gravity;

import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.model.entity.UpdateEntity;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.InstallEvent;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.util.LogUtil;


import org.greenrobot.eventbus.EventBus;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class UpdateUtilsForeground {

    public static void getNewVersion(AppActivity context, UpdateEntity updateEntity, File file, String fileName) {
        loadNewVersionProgress(context, updateEntity.getDownload_url(), file, fileName);
    }

    private static void loadNewVersionProgress(AppActivity context, final String uri, File filePush, String fileName) {
        final ProgressDialog pd;
        pd = new ProgressDialog(context);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("正在下载更新");
        pd.getWindow().setGravity(Gravity.CENTER_HORIZONTAL);
        pd.setCanceledOnTouchOutside(false);
        pd.setProgressNumberFormat("%1d Mb /%2d Mb");//这里设置的是进度条下面显示的文件大小和下载了多
        pd.show();
        new Thread() {
            @Override
            public void run() {
                try {
                    //判断是否有已下载完成的包

                    long fileSize = MkvUtils.get().getLong(MkvUtils.CommomData,fileName);
                    if (fileSize > 0){
                        File file = new File(Environment.getExternalStorageDirectory(), fileName);
                        long length = file.length();
                        if (fileSize == length){
                            install(context, file);
                            pd.dismiss();
                        }else {
                            File files = getFileFromServer(uri, filePush, fileName, pd);
                            sleep(3000);
                            install(context, files);
                            pd.dismiss();
                        }
                    }else {
                        File file = getFileFromServer(uri, filePush, fileName, pd);
                        sleep(3000);
                        install(context, file);
                        pd.dismiss();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private static File getFileFromServer(String uri, File filePash, String fileName, ProgressDialog pd) throws Exception {
        //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            URL url = new URL(uri);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            pd.setMax(conn.getContentLength() / (1024 * 1024));
            InputStream is = conn.getInputStream();

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                long contentLengthLong = conn.getContentLengthLong();

                MkvUtils.get().putLong(MkvUtils.CommomData,fileName,contentLengthLong);
            }

//            File file = new File(filePash, fileName);
            File file = new File(Environment.getExternalStorageDirectory(), fileName);
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            int total = 0;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                total += len;
                pd.setProgress(total / (1024 * 1024));
                LogUtil.i("test", total / (1024 * 1024) + "");
            }
            fos.close();
            bis.close();
            is.close();
            return file;
        } else {
            return null;
        }
    }

    private static void install(Activity context, File apkFile) {
        EventBus.getDefault().postSticky(InstallEvent.make(EventConstant.EVENT_INSTALL_APP, apkFile.getPath()));
    }

}

